package com.awesome.spring.mq;

import com.alibaba.fastjson.JSON;
import com.awesome.spring.bean.Order;
import com.awesome.spring.service.AccountService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @program: awesome-spring
 * @description: 订单消费
 * @author: Alex Wu
 * @createDate: 2025-02-13 14:38
 **/
@Slf4j
@RocketMQMessageListener(topic = "tx-order-topic", consumerGroup = "tx-order-consumer-group",
        maxReconsumeTimes = 3)  // 配置死信队列最好配置最大消费次数，否则按照16次计算
@Service
public class OrderConsumer implements RocketMQListener<String> {

    @Autowired
    private AccountService accountService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    private  Lock lock = new ReentrantLock();
    @Override
    public void onMessage(String message) {
        Order order = JSON.parseObject(message, Order.class);
        log.info("消费订单消息: {}", order);
        // 处理业务逻辑
        // 分布式锁--此处应用分布式锁，保证消息幂等性
//        RLock lock = redissonClient.getLock("order-lock:" + order.getUserId());  // 针对每个用户的订单进行锁定
        lock.lock();
        try {
            String reduceResult = accountService.reduce(order.getUserId(), order.getMoney());
            if (reduceResult.equals("ok")) {
                log.info("订单扣减成功");
            } else {
                throw new RuntimeException("订单扣减失败");
            }
        }catch (Exception e) {
            log.info("订单扣减失败");
            // 此处有两种方案：
            // 1. 抛出异常，让消息重试，直到成功，默认重试3次，如果失败，则消息进入死信队列，需要人工介入，简单实现
             throw new RuntimeException("订单扣减失败");
            // 2. 通知上游服务，订单扣减失败，让上游服务进行补偿操作或者回滚操作，但此种方案需要上游服务支持，复杂实现
//            rocketMQTemplate.convertAndSend("order-fail-topic",  JSON.toJSONString(order));
        }
         finally {
            lock.unlock();
        }
    }
}
